package com.jweb.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jweb.core.JWebFilter;
import com.jweb.util.FormatUtil;
import com.jweb.util.PathUtil;

/**
 * 框架配置类，
 * 
 * @author Yuanqy
 *
 */
public abstract class JWebConfig {

	public abstract void configConstant(Map<String, String> constants) throws Exception;

	public abstract void configPlugin(Plugins plugins) throws Exception;

	private Logger log = LoggerFactory.getLogger(getClass());

	/** 获取常量 */
	protected String getConstant(String key) {
		if (JWebFilter.getConstants() != null)
			return JWebFilter.getConstants().get(key).trim();
		return null;
	}

	/** 获取Int类型常量 */
	protected int getConstantInt(String key) {
		try {
			return Integer.parseInt(getConstant(key));
		} catch (Exception e) {
			throw new ClassCastException("getConstantInt(" + key + ") can't cast to int.");
		}
	}

	/**
	 * 加载配置文件app.properties 配置文件在web.xml里配置
	 */
	public void loadPropertyFile(String files, Map<String, String> constants) {
		if (FormatUtil.isEmpty(files)) {
			log.info("[警告]未设置配置文件：propertyFile");
			return;
		}
		files = FormatUtil.trimAll(files);
		String[] fs = files.split(";");
		for (int i = 0; i < fs.length; i++) {
			String file = fs[i];
			int index = file.indexOf(":");
			String propPath = "";
			if (index < 0)
				propPath = PathUtil.getWebRootPath() + "/" + ((file.charAt(0) == '/') || (file.charAt(0) == '\\') ? "WEB-INF" : "") + file;
			else if (file.substring(0, index).equalsIgnoreCase("classpath"))
				propPath = PathUtil.getRootClassPath() + "/" + file.substring(index + 1, file.length());
			else if (file.substring(0, index).equalsIgnoreCase("file")) {
				propPath = "/" + file.substring(index + 1, file.length());
			}
			propPath = FormatUtil.formatPath(propPath);
			try {
				InputStream is = new FileInputStream(new File(propPath));
				Properties prop = new Properties();
				prop.load(is);
				log.info("propertyFile[{}]:{}", i + 1, propPath);
				for (Entry<Object, Object> entry : prop.entrySet()) {
					constants.put(entry.getKey().toString(), entry.getValue().toString());
					log.debug("\t{}={}", entry.getKey(), entry.getValue());
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
